import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import {resolve} from 'path'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@': resolve(__dirname, 'src'),
        },
        extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    server: {
        host: '0.0.0.0',
        port: 5173,
        strictPort: false,
        hmr: {
            overlay: true,
        },
        open: true,
        cors: true,
        proxy: {
            '/api': {
                target: 'http://localhost:8081',
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path,
                // 超时设置为60秒，避免导出大文件超时
                timeout: 60000,
                configure: (proxy, options) => {
                    // 添加代理日志
                    proxy.on('error', (err, req, res) => {
                        console.error('API代理错误:', err.message);
                        console.error('代理错误详情:', err);
                        console.error('请求路径:', req.url);
                        console.error('请求方法:', req.method);
                        // 打印请求头
                        console.error('请求头:', req.headers);
                    });

                    // 仅在必要时记录请求和响应信息
                    proxy.on('proxyReq', (proxyReq, req, res) => {
                        // 对导出请求做特殊处理
                        if (req.url?.includes('export')) {
                            // 使用代理的timeout配置而不是直接设置proxyReq.timeout
                            // 导出请求需要更长的处理时间

                            // 保留Authorization头
                            const authHeader = req.headers['authorization'];
                            if (authHeader) {
                                proxyReq.setHeader('Authorization', authHeader);
                            } else {
                                console.warn('警告: 导出请求未携带认证头');
                            }

                            // 传递额外的导出标记
                            if (req.headers['x-export-request']) {
                                proxyReq.setHeader('X-Export-Request', req.headers['x-export-request']);
                            }
                        }
                        // 捕获认证相关请求
                        else if (req.url?.includes('auth')) {
                            // 保留Authorization头
                            const authHeader = req.headers['authorization'];
                            if (authHeader) {
                                proxyReq.setHeader('Authorization', authHeader);
                            }
                        }
                    });

                    proxy.on('proxyRes', (proxyRes, req, res) => {
                        // 对导出请求特殊处理
                        if (req.url?.includes('export')) {
                            // 如果是401或其他错误
                            if (proxyRes.statusCode >= 400) {
                                let body = '';
                                proxyRes.on('data', function (chunk) {
                                    body += chunk;
                                });
                                proxyRes.on('end', function () {
                                    // 确保错误响应的content-type是JSON
                                    if (proxyRes.headers['content-type']?.includes('json')) {
                                        res.setHeader('Content-Type', 'application/json;charset=utf-8');
                                    }
                                });
                            }
                        }
                        // 只记录错误响应
                        else if (proxyRes.statusCode >= 400) {
                            let body = '';
                            proxyRes.on('data', function (chunk) {
                                body += chunk;
                            });
                            proxyRes.on('end', function () {
                                try {
                                    // 处理错误响应
                                } catch (e) {
                                    // 处理解析异常
                                }
                            });
                        }
                    });
                }
            }
        }
    },
    build: {
        outDir: 'dist',
        assetsDir: 'assets',
        sourcemap: false,
        minify: 'terser',
        rollupOptions: {
            output: {
                manualChunks: {
                    vendor: ['vue', 'vue-router', 'pinia'],
                    antd: ['ant-design-vue'],
                    elementPlus: ['element-plus']
                }
            }
        },
        terserOptions: {
            compress: {
                drop_console: false,
                drop_debugger: false
            }
        }
    },
    optimizeDeps: {
        include: ['vue', 'vue-router', 'pinia', 'ant-design-vue', 'element-plus', 'axios']
    },
    logLevel: 'info',
    clearScreen: false
}) 